﻿
using System.Globalization;
using System.Windows.Controls;

namespace MuddyBoots.GreenlightQC.Mobile.UI.View.Validators
{
    public sealed class NumberValidationRule : ValidationRule
    {
        private const NumberStyles Styles = NumberStyles.AllowDecimalPoint |
                            NumberStyles.AllowLeadingSign |
                            NumberStyles.AllowExponent |
                            NumberStyles.Float |
                            NumberStyles.AllowTrailingWhite |
                            NumberStyles.AllowLeadingWhite;

        public override ValidationResult Validate(object value, CultureInfo cultureInfo)
        {
            if (value == null)
            {
                return ValidationResult.ValidResult;
            }

            if (string.IsNullOrWhiteSpace(value.ToString()))
            {
                return ValidationResult.ValidResult;
            }

            var stringValue = value.ToString();
            // igore if only the sign has been typed...
            if (stringValue == "-" || stringValue == "+")
            {
                return ValidationResult.ValidResult;
            }

            double result;
            if (double.TryParse(stringValue, Styles, cultureInfo.NumberFormat, out result))
            {
                if (result >= -100.00 && result <= 100)
                {
                    return ValidationResult.ValidResult;
                }
            }

            var message = Resources.MainWindow.invalidInput;
            return new ValidationResult(false, message);
        }
    }
}
